<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Desktop extends Controller_Initial_Page {
    
    public function action_index($url)
    {
         $user_model = ORM::factory('user');
         $user_model->with('user_profile')
                    ->where('url','=',$url)
                    ->find();
         
         $my_user_model = Auth::instance()->get_user();
          
         if(!$user_model->loaded())
                    throw new HTTP_Exception_404;
                  
         $privacy = Privacy::factory($my_user_model ? $my_user_model->id : false,
                                     $user_model->id);            
          
         $send_message_permission = $privacy->send_message_permission(); //check permission to send message
         $send_invitation_permission = $privacy->send_invitation_permission(); //check permission to send invitation
        
         $desktop_model = $user_model->desktop;
         $content_view = View::factory('toolbar');
         $desktop_view = View::factory('desktop'); 
         $account_profile_navigation_view = View::factory('account/profile_navigation');
         
         $account_profile_navigation_view->set('desktop',1)
                                         ->set('profile', $user_model->user_profile)
                                         ->set('add_to_contacts', $send_invitation_permission)
                                         ->set('message', $send_message_permission);
         
         $desktop_view->set('color',$desktop_model->color)
                      ->set('wallpaper_path',$desktop_model->wallpaper->path(true,'default',false))
                      ->set('grid',$desktop_model->grid)
                      ->set('profile_navigation',$account_profile_navigation_view);

            
         $content_view->set('content', $desktop_view );
         $this->template->set('body',$content_view);  
            
    }

    public function action_ajax_index()
    {
        $user_model = Auth::instance()->get_user();
        $referrer = parse_url($this->request->referrer());


        if($referrer) {
            $referrer_uri =  'localhost'.$referrer['path'];//$referrer['host'].$referrer['path'];
            $params = $this->request->route()->matches($referrer_uri);
            
            if($params)
            {
                $referrer_model =  ORM::factory('user')->with('user_profile')
                                                       ->where('url','=',$params['id'])
                                                       ->find();

                $edit = ($user_model AND $user_model->loaded() AND $user_model->user_profile->url === $params['id']);
                
                // get desktop items
                $item_model = ORM::factory('desktop_item');
                $items = $item_model->get_items($referrer_model->desktop->id);
                
                $output= array('success'   => true,
                               'edit'      => $edit,
                               'items'    => $items);
                               
                $this->response->body(json_encode($output));
            }
            else
            { 
                throw new HTTP_Exception_404;     
            }
        }    
    }
    
    /**
     * show edit item form
     */
    public function action_ajax_edit()
    {        
        if($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $desktop_item_model = ORM::factory('desktop_item');
            $item_model = ORM::factory('desktop_item');
            $item_data = $item_model->get_item($_POST['id'],$_POST['type']);
            
            if($item_data)
            {
                $edit_prompt_view = View::factory('project/modal_edit');
                
                if($_POST['type'] === 'project')
                {                               
                    $field_model = ORM::factory('field');
                    $fields = $field_model->get_all();
                   
                    $edit_prompt_view->set('fields', $fields);
                }
                
                $edit_prompt_view->set('type', $_POST['type']);
                $edit_prompt_view->set('data',$item_data);
                
                $content = array('success' => true,
                                 'content' => $edit_prompt_view->render());
                $this->response->body(json_encode($content));
            }
            else
            {
                throw new HTTP_Exception_404;
            }
        } 
        
    }
        
    
    
    /**
     * edit item on desktop 
     */
    public function action_ajax_edit_item()
    {
        if ($_POST)
        {
            //start transation
            $db = Database::instance();
            $db->begin();
            
            $user_model = Auth::instance()->get_user();
            
            try
            {
                //check if we have perimission to do this action 
                $desktop_item = ORM::factory('desktop_item')->get_item($_POST['id'],$_POST['type']);
                if(!$desktop_item OR !$desktop_item['user_id'] === $user_model->id)
                {
                    $db->rollback();
                    $output = array('success' => false,
                                    'message' => 'Errors during removing item');

                     $this->response->body(json_encode($output));
                     return;
                }
                           
                if($_POST['iconData']['changed'])
                {
                    // icon upload
                    $icon_id = $_POST['iconData']['id'];
                    $icon_path = $_POST['iconData']['src'];

                    $file_model = ORM::factory('file', $icon_id);
                    if($file_model->loaded()) //if icon from from harddrive 
                    {
                        $file_model->tag = null;
                        $file_model->save(); 
                    }
                    else // if icon is loaded iconfinder
                    { 
                        $file = Uploader::factory($icon_path);
                        $errors = $file->validate('150K', array('ico','png'));

                        if(!$errors)
                        {
                           // save file info in db 
                           $file_model->name      = 'icon_'.time();
                           $file_model->extension = $file->extension;
                           $file_model->size      = $file->size;
                           $file_model->folder    = 'desktop_icons/user_'.$user_model->id;    
                           $file_model->save();

                           //save icon on serwer
                           $target_directory = UPLPATH.'desktop_icons/user_'.$user_model->id.'/';  

                           $new_file_name = $file_model->id;
                           $ext = $file_model->extension;

                            // if directory doesn't exist - create 
                            if(!is_dir($target_directory))
                                mkdir($target_directory, 0755, true);

                            $image = Image::factory($file->tmp_name); 
                            $image->resize(48, 48,Image::INVERSE);
                            $image->crop(48, 48);
                            $image->save($target_directory.$new_file_name.'.'.$ext);

                        }
                        else
                        {   
                            $db->rollback();
                            $output = array('success'   => false,
                                            'errors'    => $errors);
                            $this->response->body(json_encode($output));
                            return;
                        }
                    }
                   
                    $file_id = $file_model->id;
                    $file_path = $file_model->path();
                }
                else
                {
                    //icon dosen't change
                    $file_id = $desktop_item['file_id'];
                    $file_path = $desktop_item['icon'];
                }
                
                
                // new item data 
                $desktop_item_model = ORM::factory('desktop_item',$_POST['id']);
                $desktop_item_model->icon_id = $file_id;
                $desktop_item_model->title = $_POST['title'];
                $desktop_item_model->description = $_POST['description'];
                $desktop_item_model->save(); 
                
                if($_POST['type'] === 'project')
                {
                    $desktop_project_model = ORM::factory('desktop_project',$desktop_item['project_id']);
                    $desktop_project_model->field_id = $_POST['field'];
                    $desktop_project_model->save();

                    $item_data = array('type' => 'project',
                                       'icon' =>  $file_path,
                                       'item_title' => $desktop_item_model->title,
                                       'description' => $desktop_item_model->description);
                }
                else if ($_POST['type'] === 'link')
                {
                    
                    $_POST['link'] = Security::xss_clean($_POST['link']); //filter before extra validation
                    $extra_rules = Validation::factory($_POST);
                    $extra_rules->rule('link', 'not_empty')
                                ->rule('link', 'max_length', array(':value', 127))
                                ->label('link', __('Link'));

                    $isEmbed = Embedmedia::factory($_POST['link']) != false;

                    $desktop_link_model = ORM::factory('desktop_link',$desktop_item['link_id']);
                    $desktop_link_model->link = $_POST['link'];
                    $desktop_link_model->embed = $isEmbed;
                    $desktop_link_model->save($extra_rules);

                    $item_data = array('type' => 'link',
                                       'icon' => $file_path,
                                       'item_title' => $desktop_item_model->title,
                                       'description' => $desktop_item_model->description, 
                                       'embed' => $isEmbed);
                }
                
                $db->commit();
                $output = array('success'=>true,
                                'data' => $item_data,
                                'message'=> __('Item successfuly changed.'));
                
                
                //delete old icon and save old file path if icon changed;
                if($_POST['iconData']['changed'])
                {
                    $file_model = ORM::factory('file',$desktop_item['file_id']);
                    $old_file_path = $file_model->real_path();
                    $file_model->delete();

                    unlink($old_file_path);
                }
                
                 // delete not linked icons (with tags)
                $temp_files = ORM::factory('file')->where('tag', '=', $user_model->id)->find_all();                
                foreach($temp_files as $temp_file)
                {
                    if(file_exists($temp_file->real_path())) 
                    {
                         unlink($temp_file->real_path());
                    }  
                }
                DB::delete('files')->where('tag', '=', $user_model->id)->execute();
                
  
            }
            catch(ORM_Validation_Exception $e)
            {
                 $db->rollback();
                 $output = array('success' => false,
                                 'message' => 'Errors during editing item',
                                 'errors'  => $e->errors('validation'));
            }
            
            $this->response->body(json_encode($output));
        }
    }
    /**
     * show add item form 
     */
    public function action_ajax_add()
    {
        $add_prompt_view = View::factory('project/modal_add');
    
        $field_model = ORM::factory('field');
        $fields = $field_model->get_all();
       
        $add_prompt_view->set('fields', $fields);
        $content = array('content' =>  $add_prompt_view->render());
        $this->response->body(json_encode($content));
    }
    
    /**
     * add item to desktop
     */
    public function action_ajax_add_item()
    {
        if ($_POST)
        {
            //start transation
            $db = Database::instance();
            $db->begin();
            
            $user_model = Auth::instance()->get_user();
            
            try
            {
                
                // icon upload
                $icon_id = $_POST['iconData']['id'];
                $icon_path = $_POST['iconData']['src'];

                $file_model = ORM::factory('file', $icon_id);
                if($file_model->loaded())
                {
                    $file_model->tag = null;
                    $file_model->save(); 
                }
                else 
                {
                    $file = Uploader::factory($icon_path);
                    $errors = $file->validate('150K', array('ico','png'));
                  
                    if(!$errors)
                    {
                       // save file info in db 
                       $file_model->name      = 'icon_'.time();
                       $file_model->extension = $file->extension;
                       $file_model->size      = $file->size;
                       $file_model->folder    = 'desktop_icons/user_'.$user_model->id;    
                       $file_model->save();
                       
                       //save icon on serwer
                       $target_directory = UPLPATH.'desktop_icons/user_'.$user_model->id.'/';  

                       $new_file_name = $file_model->id;
                       $ext = $file_model->extension;

                        // if directory doesn't exist - create 
                        if(!is_dir($target_directory))
                            mkdir($target_directory, 0755, true);

                        $image = Image::factory($file->tmp_name); 
                        $image->resize(48, 48,Image::INVERSE);
                        $image->crop(48, 48);
                        $image->save($target_directory.$new_file_name.'.'.$ext);

                    }
                    else
                    {   
                        $db->rollback();
                        $output = array('success'   => false,
                                        'errors'    => $errors);
                        $this->response->body(json_encode($output));
                        return;
                    }
                }
                
                $temp_files = ORM::factory('file')->where('tag', '=', $user_model->id)->find_all();                
                foreach($temp_files as $temp_file)
                {
                    if(file_exists($temp_file->real_path())) 
                    {
                         unlink($temp_file->real_path());
                    }  
                }
                DB::delete('files')->where('tag', '=', $user_model->id)->execute();

                $desktop_item_model = ORM::factory('desktop_item');
                $desktop_item_model->desktop_id = $user_model->desktop->id;
                $desktop_item_model->icon_id = $file_model->id;
                $desktop_item_model->title = $_POST['title'];
                $desktop_item_model->description = $_POST['description'];
                
                                 
                $desktop_item_model->save();
                
                if($_POST['type'] === 'project')
                {
                    $desktop_project_model = ORM::factory('desktop_project');
                    $desktop_project_model->licence_id = 1;
                    $desktop_project_model->item_id = $desktop_item_model->id;
                    $desktop_project_model->field_id = $_POST['field'];
                    $desktop_project_model->save();

                    $item_data = array('type' => 'project',
                                       'icon' =>  $file_model->path(),
                                       'item_title' => $desktop_item_model->title,
                                       'description' => $desktop_item_model->description, 
                                       'field' => $desktop_project_model->field_id,
                                       'item_id' => $desktop_item_model->id,
                                       'project_id' => $desktop_project_model->id,
                                       'project_licence' => $desktop_project_model->licence_id);
                }
                else if ($_POST['type'] === 'link')
                {
                    
                    $_POST['link'] = Security::xss_clean($_POST['link']); //filter before extra validation
                    $extra_rules = Validation::factory($_POST);
                    $extra_rules->rule('link', 'not_empty')
                              ->rule('link', 'max_length', array(':value', 127))
                              ->label('link', __('Link'));

                    $isEmbed = Embedmedia::factory($_POST['link']) != false;

                    $desktop_link_model = ORM::factory('desktop_link');
                    $desktop_link_model->link = $_POST['link'];
                    $desktop_link_model->item_id = $desktop_item_model->id;
                    $desktop_link_model->embed = $isEmbed;
                    $desktop_link_model->save($extra_rules);

                    $item_data = array('type' => 'link',
                                       'icon' => $file_model->path(),
                                       'item_title' => $desktop_item_model->title,
                                       'description' => $desktop_item_model->description, 
                                       'item_id' => $desktop_item_model->id,
                                       'link_id' => $desktop_link_model->id,
                                       'link' => $desktop_link_model->link,
                                       'embed' => $isEmbed);
                }
                $db->commit();
                $output = array('success'=>true,
                                'data' => $item_data,
                                'message'=>'Item successfuly added.');
            }
            catch(ORM_Validation_Exception $e)
            {
                 $db->rollback();
                 $output = array('success' => false,
                                 'message' => 'Errors during adding item',
                                 'errors'  => $e->errors('validation'));
            }
            
            $this->response->body(json_encode($output));
        }
    }
    

    public function action_ajax_remove_item()
    {
        if ($_POST)
        {
            $user_model = Auth::instance()->get_user();
             
            try
            {
                $desktop_item_model = ORM::factory('desktop_item', $_POST['id']);
                
                if($desktop_item_model->loaded() && $desktop_item_model->desktop->user_id === $user_model->id)
                {
                    $desktop_item_model->delete();

                    $output = array('success' => true,
                                    'message' => 'Item successfuly removed.');

                    
                }
                else
                {
                    $output = array('success' => false,
                                    'message' => 'Errors during removing item');
                } 

            }
            catch(ORM_Validation_Exception $e)
            {
                $output = array('success' => false,
                                'message' => 'Errors during removing item',
                                'errors'  => $e->errors('validation'));
            }
            
            $this->response->body(json_encode($output));
        }
    }
    
    public function action_ajax_upload_icon()
    {   
        if($_GET)
        {
            $user_model = Auth::instance()->get_user();
            $edit_mode = $user_model->loaded();
            
            $file = Uploader::factory();
            $errors = $file->validate('50K', array('ico','png'));

            if(!$errors && $edit_mode)
            {
               // save file info in db 
               $file_model = ORM::factory('file');
               $file_model->name      = $file->name;
               $file_model->extension = $file->extension;
               $file_model->size      = $file->size;
               $file_model->folder    = 'desktop_icons/user_'.$user_model->id;  
               $file_model->tag       = $user_model->id;   
               $file_model->save();
               
               //save icon on serwer
               $target_directory = UPLPATH.'desktop_icons/user_'.$user_model->id.'/';  

               $new_file_name = $file_model->id;
               $ext = $file_model->extension;

                // if directory doesn't exist - create 
                if(!is_dir($target_directory))
                    mkdir($target_directory, 0755, true);

                $image = Image::factory($file->tmp_name);
                $image->resize(48, 48,Image::INVERSE);
                $image->crop(48, 48); 
                $image->save($target_directory.$new_file_name.'.'.$ext);

                $output = array('success'   => true,
                                'icon_id'        => $file_model->id,
                                'icon_path' => $file_model->path());

            }
            else
            {
                $output = array('success'   => false,
                                'errors'    => $errors);
            }

            $this->response->body(json_encode($output));

        } 
    }

    public function action_upload_icon()
    {
        $this->auto_render = false;
        $this->action_ajax_upload_icon();  
    }
    
    public function action_ajax_update_layout()
    {
        if ($_POST)
        {
            //start transation
            $db = Database::instance();
            $db->begin();
            
            $user_model = Auth::instance()->get_user();
            $content = array();
            
            try
            {       
                if(isset($_POST['panels']))
                {
                    foreach ($_POST['panels'] as $panel)
                    {
                       $panel_model = ORM::factory('desktop_panel',$panel['id']);
                     
                       //check if allowed to process this panel 
                       if ($panel['state'] != 'new' AND (!$panel_model->loaded() OR $panel_model->desktop->user_id != $user_model->id))
                       {
                           $db->rollback();
                           throw new HTTP_Exception_403;
                       } 
                       elseif ($panel['state'] == 'delete')
                       {
                           $panel_model->delete();
                       }
                       elseif ($panel['state'] == 'update' OR $panel['state'] == 'new')
                       {
                          $panel['desktop_id'] = $user_model->desktop->id;
                          $panel_model->values($panel, array('title', 
                                                              'pos_x', 
                                                              'pos_y', 
                                                              'width', 
                                                              'height', 
                                                              'rows', 
                                                              'columns',
                                                              'desktop_id'));
                           $panel_model->save();
                           $panel_id = $panel_model->id;

                           $content[] = array('panel_id' => $panel_id,
                                             'panel_ref_id' => $panel['ref_id']);

                           if(isset($_POST['items']))
                           {
                               foreach ($_POST['items'] as $key => $item)
                               {
                                   $item_model = ORM::factory('desktop_item', $item['id']);

                                   //check if allowed to process this item
                                   if (!$item_model->loaded() OR $item_model->desktop->user_id != $user_model->id)
                                   {
                                       $db->rollback();
                                       throw new HTTP_Exception_403;
                                   }

                                   if ($item['panel_ref_id'] == $panel['ref_id'])
                                   {
                                       $item['panel_id'] = $panel_id;
                                       $item_model->values($item, array('pos_x', 
                                                                        'pos_y',
                                                                        'panel_id'));
                                       $item_model->save();
                                       unset($_POST['items'][$key]);     
                                   }      
                               }
                           }
                           else
                           {
                               $db->rollback();
                               throw new HTTP_Exception_403;
                           }  
                       }
                       else
                       {
                           $db->rollback();
                           throw new HTTP_Exception_403;
                       }               
                    }
                }

                if(isset($_POST['items']))
                {
                    foreach($_POST['items'] as $item)
                    {
                        $item_model = ORM::factory('desktop_item', $item['id']);

                        //check if allowed to process this item
                        if (!$item_model->loaded() OR $item_model->desktop->user_id != $user_model->id)
                        {
                            $db->rollback();
                            throw new HTTP_Exception_403;
                        }

                         $item['panel_id'] = null;
                         $item_model->values($item, array('pos_x', 
                                                          'pos_y',
                                                          'panel_id'));
                         $item_model->save();
                    }
                } 
                // else
                // {
                //       $db->rollback();
                //       throw new HTTP_Exception_403;
                // }
                
                //all ok
                $db->commit();
                $output = array('success' => true,
                                'message' => __('Desktop saved'),
                                'content' => $content);
                                
                $this->response->body(json_encode($output));
                return $output;

            }
            catch (ORM_Validation_Exception $e)
            {
                 $db->rollback();
                 throw new HTTP_Exception_403;
            }
               
        }
    }
}
